package kr.moiba.openapi.web;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;


/**
 * @author 이 영호(Youngho Lee)
 */

@Controller
@RequestMapping(value={"/openapi"})
public class OpenApiCtrl {
	
	private final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private MessageSourceAccessor messages;

	@RequestMapping("/addrNumber.do")
	public @ResponseBody Map<String, Object> addrNumber(@RequestParam(required=true, value="text") String text) throws Exception {
		
		String apiurl = messages.getMessage("openapi.url.post");
		String regkey = messages.getMessage("openapi.keys.post");

        HttpURLConnection conn = null;
        InputStream in = null;
        ByteArrayOutputStream baos = null;
        
        ArrayList<String[]> addressInfo = new ArrayList<String[]>();
        String result = "";
        try{
            StringBuffer sb = new StringBuffer(3);
            sb.append(apiurl);
            sb.append("?regkey="+regkey+"&target=post&query=");
            sb.append(URLEncoder.encode(text.trim(),"EUC-KR"));
            String query = sb.toString();
            
            URL url = new URL(query);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("accept-language","ko");
            
            byte[] bytes = new byte[4096];
            in = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            while(true){
                int red = in.read(bytes);
                if(red < 0)
                    break;
                baos.write(bytes, 0, red);
            }
            result = baos.toString("euc-kr");
            
            DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = docBuilder.parse(new InputSource(new StringReader(result)));
            
            Element el = (Element)doc.getElementsByTagName("itemlist").item(0);
            if(el != null){
            	for(int i=0; i<el.getChildNodes().getLength(); i++){
                    Node node = el.getChildNodes().item(i); 
                    if(!node.getNodeName().equals("item")){
                        continue;
                    }
                    String address = node.getChildNodes().item(1).getFirstChild().getNodeValue();
                    String post = node.getChildNodes().item(3).getFirstChild().getNodeValue();
                    
                    addressInfo.add(new String[]{post.substring(0, 3), post.substring(4), address});
                }	
            }
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
        	if(conn != null) conn.disconnect();
        	if(in != null) in.close();
        	if(baos != null) baos.close();
        }
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("addressInfo", addressInfo);
        
		return resultMap;
	}
	
/*
	@RequestMapping("/addrNumber.do")
	public @ResponseBody ArrayList<String[]> addrNumber(@RequestParam(required=true, value="text") String text) throws Exception {
		
		String apiurl = messages.getMessage("openapi.url.post");
		String regkey = messages.getMessage("openapi.keys.post");

        HttpURLConnection conn = null;
        InputStream in = null;
        ByteArrayOutputStream baos = null;
        
        String result = "";
        ArrayList<String[]> addressInfo = new ArrayList<String[]>();
        try{
            StringBuffer sb = new StringBuffer(3);
            sb.append(apiurl);
            sb.append("?regkey="+regkey+"&target=post&query=");
            sb.append(URLEncoder.encode(text.trim(),"EUC-KR"));
            String query = sb.toString();
            
            URL url = new URL(query);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("accept-language","ko");
            
            byte[] bytes = new byte[4096];
            in = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            while(true){
                int red = in.read(bytes);
                if(red < 0)
                    break;
                baos.write(bytes, 0, red);
            }
            result = baos.toString("euc-kr");
            
            DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = docBuilder.parse(new InputSource(new StringReader(result)));
            
            Element el = (Element)doc.getElementsByTagName("itemlist").item(0);
            
            for(int i=0; i<el.getChildNodes().getLength(); i++){
                Node node = el.getChildNodes().item(i); 
                if(!node.getNodeName().equals("item")){
                    continue;
                }
                String address = node.getChildNodes().item(1).getFirstChild().getNodeValue();
                String post = node.getChildNodes().item(3).getFirstChild().getNodeValue();
                
                addressInfo.add(new String[]{post.substring(0, 3), post.substring(4), address});
            }
            
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
        	if(conn != null) conn.disconnect();
        	if(in != null) in.close();
        	if(baos != null) baos.close();
        }
System.out.println(addressInfo.toString());
		return addressInfo;
	}
 * */

}